package cn.zyy.jdbc.test;

import cn.zyy.jdbc.util.DruidUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * jdbc中的事务  commit rollback
 */
public class TransactionTest01 {
    public static void main(String[] args) {
        Connection connection = DruidUtil.getConnection();
        try {
            //关闭事物的自动提交
            connection.setAutoCommit(false);
            String sql = "update account  set money = money - ?  where  id =  ? ";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setObject(1,500 );
            preparedStatement.setObject(2, 1);
            int line = preparedStatement.executeUpdate();
            System.out.println("line1 = " + line);
            //int i = 1/0;
            preparedStatement.setObject(1, -500);
            preparedStatement.setObject(2, 2);
            line = preparedStatement.executeUpdate();
            System.out.println("line2 = " + line);
            //手动提交事物
            connection.commit();
        }catch (Exception e){
            e.printStackTrace();
            try {
                //事务的回滚
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
    }
}
